<!-- 登录授权 -->
<template>
	<view class="xjx-login">
		<button
			v-if="canIUseGetUserProfile"
			class="login-button"
			@click="getWxUserInfoNew"
		>
			<slot name="loginBtn"></slot>
		</button>
		<button
			v-else
			class="login-button"
			open-type="getUserInfo"
			@getuserinfo="getWxUserInfo($event)"
		>
			<slot name="loginBtn"></slot>
		</button>
		<!-- 下拉选择 -->
		<!-- <view v-show="popupShow">
			<view class="popup-view">
				<image class="popup-logo" :src="'../../../static/images/logo-blue.png'|addBaseImgUrl" mode=""></image>
				<view class="popup-tips">申请获得你微信绑定的手机号</view>
				<button class="popup-btn" open-type="getPhoneNumber" @getphonenumber="getWxPhoneNumber">获取手机号</button>
			</view>
		</view> -->
		<uni-popup ref="popup" type="bottom">
			<view class="popup-view">
				<view @click="closePopup" class="popup-close">
					<image :src="'../../static/images/icon-close-grey.png'" mode=""></image>
				</view>
				<image class="popup-logo" :src="'@/static/images/logo-new.png'|addBaseImgUrl" mode=""></image>
				<view class="popup-tips">申请获得你微信绑定的手机号</view>
				<button 
					open-type="getPhoneNumber"
					@getphonenumber="onGetPhoneNumber">
					获取手机号
				</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	/**
	 * xjx-login
	*/
	import { mapState, mapGetters, mapMutations } from 'vuex'
	export default {
		name: 'XjxLogin',
		props: {
			title: {
				type: String,
				default: ''
			},
			loginToEmit: { // 如果未登录，登录完是否直接调用callBack
				type: Boolean,
				default: false
			},
			callBack: {
				type: Function,
				default: null
			},
			recUser: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				wxUserInfo: null,
				wxPhoneNumberInfo: null,
				canIUse: uni.canIUse('button.open-type.getUserInfo'),
				canIUse1: uni.canIUse('button.open-type.getPhoneNumber'),
				canIUseGetUserProfile: false,
				popupShow: false,
				wxLoginCode: '',
				timer: '',
				clickFlag: true
			}
		},
		mounted(){
			if (wx.getUserProfile) {
			  this.canIUseGetUserProfile = true
			}
			this.wxLogin()
		},
		computed:{
			...mapState(['userInfo','accessToken']),
		},
		methods:{
			...mapMutations(['setStateAttr','loginOut']),
			closePopup(){
				this.$refs.popup.close()
			},
			onGetPhoneNumber(e) {
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					wx.cloud.callFunction({
					name: 'getPhoneNumber',
					data: {
						cloudID: e.detail.cloudID
					},
					success: res => {
						console.log('手机号信息：', res.result.list[0])
					}
					})
				} else {
					console.warn('用户拒绝授权或无权限', e.detail)
				}
				},

			wxLogin() {
				const _this = this
				uni.login({
					provider:'weixin',
					success(loginRes) {
						_this.wxLoginCode = loginRes.code
						_this.timer = setTimeout(()=>{
							_this.wxLogin()
							clearTimeout(_this.timer)
						},300000)
					},
					fail(err) {
						console.error('Login failed', err)
					}
				})
			},
			getWxUserInfo(e) {
				if (e.detail.userInfo) {
					this.wxUserInfo = e.detail.userInfo
					this.popupShow = true
					this.$refs.popup.open()
				}
			},
			getWxUserInfoNew() {
				if (this.accessToken) {
					this.$api.getUserInfo({
						'ACCESS-TOKEN': this.accessToken
					}).then(res => {
						if (res && res.code == 200) {
							this.$emit('callBack')
						} else if (res && res.code == 401) {
							this.getUserProfile()
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					}).catch(err => {
						console.error('Error fetching user info', err)
					})
				} else {
					this.getUserProfile()
				}
			},
			getUserProfile() {
				uni.getUserProfile({
					desc: '用于完善用户资料',
					success: (res) => {
						this.wxUserInfo = res.userInfo
						this.popupShow = true
						this.$refs.popup.open()
					},
					fail: (err) => {
						console.error('Failed to get user profile', err)
					}
				})
			},
			storeUserInfo() {
				if (!this.wxPhoneNumberInfo) {
					console.error('Phone number info is not set')
					wx.showToast({
						title: '手机号信息缺失',
						icon: 'none'
					})
					return
				}
				wx.cloud.callFunction({
					name: 'getPhoneNumber',
					data: {
						encryptedData: this.wxPhoneNumberInfo.encryptedData,
						iv: this.wxPhoneNumberInfo.iv
					},
					success: res => {
						if (res.result.success) {
							const userInfo = {
								...this.wxUserInfo,
								phoneNumber: res.result.data.phoneNumber
							}
							const db = wx.cloud.database()
							db.collection('users').add({
								data: userInfo
							}).then(() => {
								this.$emit('callBack')
								wx.showToast({
									title: '登录成功',
									icon: 'success'
								})
							}).catch(err => {
								console.error('Database storage failed', err)
								wx.showToast({
									title: '存储失败',
									icon: 'none'
								})
							})
						} else {
							wx.showToast({
								title: '获取手机号失败',
								icon: 'none'
							})
						}
					},
					fail: err => {
						console.error('Cloud function call failed', err)
						wx.showToast({
							title: '调用失败',
							icon: 'none'
						})
					}
				})
			},
			getWxPhoneNumber(e) {
				console.log('eeee', e)
				if (e.detail.iv) {
					this.wxPhoneNumberInfo = e.detail;
					// 调用云函数来解密手机号并获取用户信息
					wx.cloud.callFunction({
						name: 'getPhoneNumber',
						data: {
							encryptedData: this.wxPhoneNumberInfo.encryptedData,
							iv: this.wxPhoneNumberInfo.iv
						},
						success: res => {
							if (res.result.success) {
								const userInfo = {
									...this.wxUserInfo,
									phoneNumber: res.result.data.phoneNumber
								};
								// 存储用户信息到数据库
								const db = wx.cloud.database();
								db.collection('users').add({
									data: userInfo
								}).then(() => {
									this.$emit('callBack');
									wx.showToast({
										title: '登录成功',
										icon: 'success'
									});
								}).catch(err => {
									console.error('数据库存储失败', err);
									wx.showToast({
										title: '存储失败',
										icon: 'none'
									});
								});
							} else {
								wx.showToast({
									title: '获取手机号失败',
									icon: 'none'
								});
							}
						},
						fail: err => {
							console.error('云函数调用失败', err);
							wx.showToast({
								title: '调用失败',
								icon: 'none'
							});
						}
					});
					this.$refs.popup.close();
				}
			},
			async loginApi(){
				let param = {
					code: this.wxLoginCode,
					...this.wxUserInfo,
					encryptedData: this.wxPhoneNumberInfo.encryptedData,
					iv: this.wxPhoneNumberInfo.iv
				}
				if(this.recUser){
					param.recUser = this.recUser
				}
				const res = await this.$api.wxLogin(param)
				if(res && res.code==200){
					this.setStateAttr([{
						key: 'accessToken',
						val: res.data.token
					},{
						key: 'userInfo',
						val: res.data.user
					}])
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					uni.setStorageSync('accessToken', res.data.token)
					uni.setStorageSync('userInfo', JSON.stringify(res.data.user))
					if(this.loginToEmit){
						this.$emit('callBack')
					}
				}else{
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					this.wxLogin()
				}
			},
		}
	}
</script>

<style lang="scss">
	.xjx-login{
		line-height: 1;
		.login-button{
			display: inline-block;
			border: none;
			padding: 0;
			background-color: transparent;
			width: 100%;
			&:after{
				border: none;
			}
		}
		
		
		.popup-view{
			height: 485px;
			border-radius: 32rpx 32rpx 0 0;
			// padding-top: 245rpx;
			background-color: white;
			position: relative;
			display: flex;
			flex-flow: column nowrap;
			align-items: center;
			justify-content: center;
			padding-bottom: 120rpx;
			.popup-close{
				padding: 30rpx;
				position: absolute;
				right: 0;
				top: 0;
				image{
					width: 28rpx;
					height: 28rpx;
					vertical-align: middle;
				}
			}
			.popup-logo{
				width: 230rpx;
				height: 230rpx;
				margin: 0 auto;
			}
			.popup-tips{
				color: $text-color-grey;
				text-align: center;
				margin-top: 20rpx;
			}
			.popup-btn{
				position: absolute;
				width: 690rpx;
				left: 50%;
				bottom: 30rpx;
				margin-left: -345rpx;
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 44rpx;
				text-align: center;
				background-color: $public-color-blue1;
				color: white;
				border: none;
				font-size: 30rpx;
				&:after{
					border: none;
				}
			}
		}
	}
</style>
